package com.android.chat.example;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smackx.muc.DiscussionHistory;
import org.jivesoftware.smackx.muc.MultiUserChat;

import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.android.chat.connection.ServerConnect;
import com.android.chat.connection.SuggestServer;

public class ChatRoomActivity extends Activity {
	public static final String CHAT_ID_KEY = "ChatID";

	private EditText txtContent;
	private Connection conn;

	private ArrayList<String> messages;
	private ListView list;
	private Handler handler = new Handler();
	MultiUserChat muc;
	boolean firstTime = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat_layout);

		// Bundle bundle = this.getIntent().getExtras();
		// mLat = bundle.getDouble("MY_LAT");
		// mLong = bundle.getDouble("MY_LONG");

		// Acquire a reference to the system Location Manager
		LocationManager locationManager = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);

		// Define a listener that responds to location updates
		LocationListener locationListener = new LocationListener() {
			public void onLocationChanged(Location loc) {
				// Called when a new location is found by the network location
				// provider.
				// makeUseOfNewLocation(location);
				double mLat = loc.getLatitude();
				double mLong = loc.getLongitude();
				
				if (!firstTime) {
					messages.add("Lat-Long: " + mLat + ", " + mLong);
					setListAdapter();
					firstTime = true;
				}

				Geocoder gcd = new Geocoder(ChatRoomActivity.this,
						Locale.getDefault());
				List<Address> addresses;
				try {
					addresses = gcd.getFromLocation(mLat, mLong, 1);
					if (addresses.size() > 0)
						// messages.add("Country: " +
						// addresses.get(0).getCountryName());
						// messages.add("Area: " +
						// addresses.get(0).getAdminArea());
						messages.add("Hệ thống: Bạn đã tham gia room "
								+ addresses.get(0).getSubAdminArea());
					setListAdapter();

					joinRoom(addresses.get(0).getSubAdminArea());
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}

			public void onStatusChanged(String provider, int status,
					Bundle extras) {

			}

			public void onProviderEnabled(String provider) {

			}

			public void onProviderDisabled(String provider) {

			}
		};

		// Register the listener with the Location Manager to receive location
		// updates
		locationManager.requestLocationUpdates(
				LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

		messages = new ArrayList<String>();

		txtContent = (EditText) findViewById(R.id.txtContent);

		list = (ListView) findViewById(R.id.listChat);

		setListAdapter();

		Button btnSend = (Button) findViewById(R.id.btnSend);

		btnSend.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String content = txtContent.getText().toString();
				sendChatMessage(content);
				txtContent.setText("");
			}
		});

	}

	private void joinRoom(String name) {
		conn = ServerConnect.getConnection();
		String room = "myroom@conference.huunc-hp";
		muc = new MultiUserChat(conn, room);

		try {

			// muc.create(conn.getUser().toString());

			// muc.sendConfigurationForm(new Form(Form.TYPE_SUBMIT));

			DiscussionHistory history = new DiscussionHistory();
			history.setMaxStanzas(2);

			muc.join(conn.getUser().toString(), "",  history,
					SmackConfiguration.getPacketReplyTimeout());

		} catch (XMPPException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		muc.addMessageListener(new PacketListener() {

			@Override
			public void processPacket(Packet packet) {
				// TODO Auto-generated method stub
				Message message = (Message) packet;
				if (message.getBody() != null) {

					String fromName = message.getFrom();
					messages.add(fromName + ": " + message.getBody());
					handler.post(new Runnable() {
						public void run() {
							setListAdapter();
						}
					});
				}
			}
		});
	}

	private void setListAdapter() {
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				R.layout.chat_row, messages);
		list.setAdapter(adapter);
		list.setSelectionFromTop(messages.size(), 0);
	}

	private void sendChatMessage(String msg) {

		try {
			Message message = muc.createMessage();
			message.setBody(msg);
			message.setType(Message.Type.groupchat);
			muc.sendMessage(message);

			// messages.add(conn.getUser().toString() + ": " + msg);

			String suggest = SuggestServer.suggest(msg);
			if (suggest != null) {
				messages.add("Server sugguest: " + suggest);
			}

			setListAdapter();
		} catch (XMPPException e) {
			e.printStackTrace();
		}
	}
}
